package com.cyzy.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cyzy.mapper.PaymentMapper;
import com.cyzy.mapper.UserMapper;
import com.cyzy.pojo.User;
import com.cyzy.pojo.Payment;
import com.cyzy.service.UserService;
import com.cyzy.utils.Md5Util;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import com.cyzy.mapper.AddressMapper;
import com.cyzy.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LIGHT
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    @Autowired
    private AddressMapper addressMapper;
    
    @Autowired
    private PaymentMapper paymentMapper;
    
    /**
     * 获取当前时间戳
     * @return 当前时间的java.sql.Timestamp对象
     */
    private java.sql.Timestamp getCurrentTimestamp() {
        try {
            return new java.sql.Timestamp(System.currentTimeMillis());
        } catch (Exception e) {
            System.err.println("获取当前时间戳异常：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 根据条件查询单个用户
     */
    private User getUserByCondition(LambdaQueryWrapper<User> queryWrapper) {
        return getOne(queryWrapper);
    }
    
    /**
     * 检查用户是否存在
     * @param userId 用户ID
     * @return 用户对象，如果不存在则返回null
     */
    private User checkUserExists(Long userId) {
        if (userId == null || userId <= 0) {
            System.err.println("用户ID不能为空或无效：" + userId);
            return null;
        }
        
        try {
            User user = getById(userId);
            if (user == null) {
                System.err.println("用户不存在：" + userId);
            } else {
                System.out.println("用户存在，ID：" + userId + "，用户名：" + user.getUserName());
            }
            return user;
        } catch (Exception e) {
            System.err.println("查询用户异常：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public User login(String username, String password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserAcc, username)
                .eq(User::getUserPassword, Md5Util.getMD5String(password))
                .eq(User::getUserStatus, 1);
        return getUserByCondition(queryWrapper);
    }

    @Override
    public User emailLogin(String email) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserEmail, email)
                .eq(User::getUserStatus, 1);
        return getUserByCondition(queryWrapper);
    }

    @Override
    public boolean addUser(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserAcc, user.getUserAcc());
        if (getUserByCondition(queryWrapper) != null) {
            return false;
        }
        
        user.setUserPassword(Md5Util.getMD5String(user.getUserPassword()));
        Timestamp now = getCurrentTimestamp();
        user.setCreatedAt(now);
        user.setUpdatedAt(now);
        String sex=user.getIdCard().substring(16,17);
        int sexNum = Integer.parseInt(sex);

        // 判断性别：奇数表示男性，偶数表示女性
        String gender;
        if (sexNum % 2 == 1) {
            gender = "男";
        } else {
            gender = "女";
        }
        user.setUserSex(gender);

        
        // 设置默认状态为1（正常）
        if (user.getUserStatus() == ' ') {
            user.setUserStatus(1);
        }
        return save(user);
    }

    @Override
    public User getUserByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            return null;
        }
        
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);
        return getUserByCondition(queryWrapper);
    }

    @Override
    @Transactional
    public boolean rechargeBalance(Long userId, Double amount) {
        if (amount <= 0) {
            System.err.println("充值金额必须大于0：" + amount);
            return false;
        }

        User user = checkUserExists(userId);
        if (user == null) {
            System.err.println("用户不存在：" + userId);
            return false;
        }

        System.out.println("开始充值处理，用户ID：" + userId + "，充值金额：" + amount);
        
        // 获取当前余额，如果为null或0则设为0
        Double currentBalance = user.getUserMoney() != ' ' && user.getUserMoney() != 0 ? user.getUserMoney() : 0.0;
        Double newBalance = currentBalance + amount;
        
        System.out.println("当前余额：" + currentBalance + "，新余额：" + newBalance);

        boolean result = updateUserBalance(userId, newBalance);
        if (result) {
            System.out.println("用户余额更新成功");
        } else {
            System.err.println("用户余额更新失败");
        }
        return result;
    }

    @Override
    public boolean pay(String userId, Long amount) {
        if (amount <= 0) {
            return false;
        }

        User user = getById(userId);
        if (user == null || user.getUserMoney() == 0 || user.getUserMoney() < amount) {
            return false;
        }
        
        Double newBalance = user.getUserMoney() - amount;
        return updateUserBalance(Long.valueOf(userId), newBalance);
    }
    
    /**
     * 更新用户余额
     */
    private boolean updateUserBalance(Long userId, Double newBalance) {
        try {
            System.out.println("准备更新用户余额，用户ID：" + userId + "，新余额：" + newBalance);
            
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getUserId, userId)
                    .set(User::getUserMoney, newBalance)
                    .set(User::getUpdatedAt, getCurrentTimestamp());
            
            boolean result = update(updateWrapper);
            if (result) {
                System.out.println("用户余额更新成功");
            } else {
                System.err.println("用户余额更新失败");
            }
            return result;
        } catch (Exception e) {
            System.err.println("更新用户余额异常：" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean forget(String email, String password) {
        if (!StringUtils.hasText(email) || !StringUtils.hasText(password)) {
            return false;
        }
        
        User user = getUserByEmail(email);
        if (user == null) {
            return false;
        }
        
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, user.getUserId())
                .set(User::getUserPassword, Md5Util.getMD5String(password))
                .set(User::getUpdatedAt, getCurrentTimestamp());
        return update(updateWrapper);
    }

    @Override
    public boolean isEmailUsed(String email) {
        if (!StringUtils.hasText(email)) {
            return false;
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserEmail, email);
        return count(queryWrapper) > 0;
    }
    
    @Override
    @Transactional
    public boolean updateUserAvatar(Long userId, String avatarFileName) {
        if (!StringUtils.hasText(avatarFileName)) {
            return false;
        }

        if (checkUserExists(userId) == null) {
            return false;
        }

        return updateUserField(userId, User::getUserAvatar, avatarFileName);
    }
    
    @Override
    @Transactional
    public boolean updateUserNickname(Long userId, String nickname) {
        if (!StringUtils.hasText(nickname) || nickname.length() < 2 || nickname.length() > 16) {
            return false;
        }
        
        if (checkUserExists(userId) == null) {
            return false;
        }
        
        return updateUserField(userId, User::getUserName, nickname);
    }
    
    /**
     * 通用方法更新用户字段
     */
    private <T> boolean updateUserField(Long userId, com.baomidou.mybatisplus.core.toolkit.support.SFunction<User, T> column, T value) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, userId)
                .set(column, value)
                .set(User::getUpdatedAt, getCurrentTimestamp());
        return update(updateWrapper);
    }

    @Override
    public boolean hasPayPassword(Long userId) {
        User user = checkUserExists(userId);
        if (user == null) {
            return false;
        }
        
        return StringUtils.hasText(user.getUserPayPwd());
    }
    
    @Override
    @Transactional
    public boolean setPayPassword(Long userId, String payPassword) {
        if (!StringUtils.hasText(payPassword) || !payPassword.matches("^\\d{6}$")) {
            return false;
        }
        
        if (checkUserExists(userId) == null) {
            return false;
        }
        
        String encryptedPayPassword = Md5Util.getMD5String(payPassword);
        return updateUserField(userId, User::getUserPayPwd, encryptedPayPassword);
    }

    @Override
    public User getUserByEmail(String email) {
        if (!StringUtils.hasText(email)) {
            return null;
        }
        
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserEmail, email);
        return getUserByCondition(queryWrapper);
    }
    
    @Override
    public boolean hasAddress(Long userId) {
        User user = checkUserExists(userId);
        if (user == null) {
            return false;
        }
        
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, userId);
        return addressMapper.selectCount(queryWrapper) > 0;
    }
    
    @Override
    public List<Payment> getRechargeRecords(Long userId) {
        if (userId == null || userId <= 0) {
            System.err.println("用户ID不能为空或无效：" + userId);
            return new ArrayList<>();
        }
        
        try {
            // 检查用户是否存在
            User user = checkUserExists(userId);
            if (user == null) {
                System.err.println("用户不存在：" + userId);
                return new ArrayList<>();
            }
            
            // 使用MyBatis-Plus的LambdaQueryWrapper直接查询
            LambdaQueryWrapper<Payment> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Payment::getUserId, userId)
                      .eq(Payment::getStatus, 1)
                      .eq(Payment::getPaymentMethod, "余额充值")
                      .orderByDesc(Payment::getCreatedAt);
            
            return paymentMapper.selectList(queryWrapper);
        } catch (Exception e) {
            System.err.println("查询充值记录异常：" + e.getMessage());
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<Payment> getConsumptionRecords(Long userId) {
        if (userId == null || userId <= 0) {
            System.err.println("用户ID不能为空或无效：" + userId);
            return new ArrayList<>();
        }
        
        try {
            // 检查用户是否存在
            User user = checkUserExists(userId);
            if (user == null) {
                System.err.println("用户不存在：" + userId);
                return new ArrayList<>();
            }
            
            // 使用MyBatis-Plus的LambdaQueryWrapper直接查询
            LambdaQueryWrapper<Payment> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Payment::getUserId, userId)
                      .eq(Payment::getStatus, 1)
                      .ne(Payment::getPaymentMethod, "余额充值")  // 不等于"余额充值"的记录
                      .orderByDesc(Payment::getCreatedAt);
            
            return paymentMapper.selectList(queryWrapper);
        } catch (Exception e) {
            System.err.println("查询消费记录异常：" + e.getMessage());
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<Payment> getPaymentRecords(Long userId) {
        if (userId == null || userId <= 0) {
            System.err.println("用户ID不能为空或无效：" + userId);
            return new ArrayList<>();
        }
        
        try {
            // 检查用户是否存在
            User user = checkUserExists(userId);
            if (user == null) {
                System.err.println("用户不存在：" + userId);
                return new ArrayList<>();
            }
            
            // 使用MyBatis-Plus的LambdaQueryWrapper直接查询
            LambdaQueryWrapper<Payment> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Payment::getUserId, userId)
                      .eq(Payment::getStatus, 1)
                      .orderByDesc(Payment::getCreatedAt);
            
            return paymentMapper.selectList(queryWrapper);
        } catch (Exception e) {
            System.err.println("查询资金流水异常：" + e.getMessage());
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
}
